<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写签名</title>
    <style>
        h1 {
            text-align: center;
        }

        canvas {
            border: 1px solid black;
            margin: 0 auto;
        }

        #clearcvs {
            border: 1px solid black;
            width: 50px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border-radius: 5px;
            transition: background-color .2s;
        }

        #clearcvs:hover {
            background-color: #bbb;
            color: #fff;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1>手写签名</h1>
    <canvas id="cvs" width="500" height="300"></canvas>
    <div id="clearcvs">清空</div>
    <script>
        const cvs = document.getElementById('cvs')
        const ctx = cvs.getContext('2d')
        let isDrawing = false
        cvs.addEventListener('mousedown', e => {
            isDrawing = true
            ctx.moveTo(e.pageX, e.pageY - cvs.offsetTop)
        })
        cvs.addEventListener('mousemove', e => {
            if (isDrawing) {
                ctx.lineTo(e.pageX, e.pageY - cvs.offsetTop)
                ctx.stroke()
            }
        })
        cvs.addEventListener('mouseup', e => {
            isDrawing = false
        })

        clearcvs.onclick = function () {
            // 当画布的宽或高被重置时，当前画布内容就会被移除
            cvs.width = 500
            cvs.height = 300
        }
    </script>
</body>

</html>